import axios from "axios";
import { Message } from "element-ui";
import { saveAs } from "file-saver";
import { getToken } from "@/utils/auth";
import configS from "@/utils/config";
import { blobValidate } from "../utils/onUtils";
import { startLoading, endLoading } from "@/plugins/loading";

export default {
  zip(url, name) {
    axios({
      method: "get",
      baseURL: configS.jBaseURL,
      url: url,
      responseType: "blob",
      headers: { token: getToken() },
    }).then(async (res) => {
      const isLogin = await blobValidate(res.data);
      if (isLogin) {
        const blob = new Blob([res.data], { type: "application/zip" });
        this.saveAs(blob, name);
      } else {
        Message.error("无效的会话，或者会话已过期，请重新登录。");
      }
    });
  },
  // 下载模板
  down(id, name, data) {
    return new Promise((resolve) => {
      startLoading();
      axios({
        method: "get",
        baseURL: configS.jBaseURL,
        url: "/base/export/template/download/" + id,
        params: data,
        responseType: "blob",
        headers: { token: getToken() },
      }).then((res) => {
        const blob = new Blob([res.data]);
        this.saveAs(blob, name);
        resolve(true);
      }).finally(() => {
        endLoading();
      });
    });
  },
  // 上传模板
  uplodFile(id, fileArr, data = {}) {
    return new Promise((resolve, error) => {
      startLoading();
      if (!fileArr.length) {
        Message.error("请先上传文件");
        error();
      }
      let formData = new FormData();
      formData.append("templateId", id);
      formData.append("file", fileArr[0].raw);
      for (const key in data) {
        formData.append(key, data[key]);
      }
      axios({
        method: "post",
        baseURL: configS.jBaseURL,
        url: "/base/export/template/importData",
        headers: { token: getToken() },
        data: formData,
      })
        .then(() => {
          Message.success("导入成功");
          resolve(true);
        })
        .catch((err) => {
          Message.error(err.response.data.message);
          error();
        })
        .finally(() => {
          endLoading();
        });
    });
  },
  // 查看
  preview(filePath, name) {
    window.open(configS.imgUrl + filePath, name);
  },
  // 下载 (链接下载)
  download(filePath, name) {
    window.open(configS.download + filePath, name);
  },
  // 下载 (二进制流文件下载)
  saveAs(text, name, opts) {
    saveAs(text, name, opts);
  },
};
